import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

const app = createApp(App)
const distance = 150
const duration = 300
function isBelowViewPort(el) {
  const rect = el.getBoundingClientRect()
  return rect.top - distance > window.innerHeight
}
const animationMap = new WeakMap()
function createSlideInDirective() {
  const ob = new IntersectionObserver((entries) => {
    for (const entry of entries) {
      if (entry.isIntersecting) {
        const animation = animationMap.get(entry.target)
        if (animation) {
          animation.play()
          ob.unobserve(entry.target)
        }
      }
    }
  })

  return {
    mounted(el) {
      if (!isBelowViewPort(el)) {
        return
      }

      const animation = el.animate(
        [
          {
            transform: `translateY(${distance}px)`,
            opacity: 0.5
          },
          {
            transform: 'translateY(0)',
            opacity: 1
          }
        ],
        {
          duration: duration,
          easing: 'ease-in-out'
        }
      )

      animation.pause()
      ob.observe(el)
      animationMap.set(el, animation)
    },
    unmounted(el) {
      ob.unobserve(el)
    }
  }
}

app.directive('slide-in', createSlideInDirective())
app.mount('#app')
